package com.demo.springai.controller;

import com.demo.springai.model.ChatRequest;
import com.demo.springai.model.ChatResponse;
import com.demo.springai.service.ChatService;
import jakarta.validation.Valid;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import reactor.core.publisher.Flux;


/**
 * 聊天控制器
 * 提供REST API，允许客户端与AI进行对话
 */
@Slf4j  // Lombok注解：自动生成日志对象
@RestController
@RequestMapping("/api/chat")
public class ChatController {

    /**
     * 聊天服务，处理对话逻辑
     */
    private final ChatService chatService;

    /**
     * 构造函数：注入聊天服务
     *
     * @param chatService 聊天服务
     */
    @Autowired
    public ChatController(ChatService chatService) {
        this.chatService = chatService;
    }

    /**
     * 处理普通聊天请求
     *
     * @param message   消息内容
     * @param model     使用的模型（可选）
     * @param sessionId 会话ID（可选）
     * @return 聊天响应
     */
    @GetMapping
    public ResponseEntity<ChatResponse> chat(
            @RequestParam(name = "message") String message,
            @RequestParam(name = "model", required = false) String model,
            @RequestParam(name = "session_id", required = false) String sessionId) {
        try {
            log.info("Received chat request: {}, model: {}, session: {}", message, model, sessionId);
            ChatRequest request = new ChatRequest(message, model);
            request.setSessionId(sessionId);

            ChatResponse response = chatService.chat(request);
            log.info("Chat response: {}", response);
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            log.error("Error while processing chat request: {}");
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(ChatResponse.error("Chat processing failed", "CHAT_ERROR"));
        }
    }

    /**
     * 处理流式聊天请求（简化版本）
     *
     * @param message   消息内容
     * @param sessionId 会话ID（可选）
     * @return 流式聊天响应
     */
    @GetMapping("/stream")
    public ResponseEntity<String> chatStream(
            @RequestParam(name = "message") String message,
            @RequestParam(name = "session_id", required = false) String sessionId) {
        try {
            log.info("Received stream chat request: {}, session: {}", message, sessionId);
            ChatRequest request = new ChatRequest(message);
            request.setSessionId(sessionId);
            String result = chatService.chatStream(request);
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            log.error("Error while processing stream chat request: {}", e.getMessage());
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body("流式聊天处理失败");
        }
    }
}
